package com.unis.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;

public class utils {
	public static ArrayList<Map<String, Map<Object, String>>> ConvertToList(ResultSet rs) {
		// 用于存放某张表的数据
		ArrayList<Map<String, Map<Object, String>>> table = new ArrayList<Map<String, Map<Object, String>>>();
		try {
			while (rs.next()) {
				// 用于存放某一列的列名和该列的值与类型
				Map<String, Map<Object, String>> rows = new HashMap<String, Map<Object, String>>();
				ResultSetMetaData rsmd = rs.getMetaData();
				for (int i = 1; i <= rsmd.getColumnCount(); i++) {
					// 用于存放某一列的值和类型
					Map<Object, String> valueTypeMap = new IdentityHashMap<Object, String>();
					String columnName = rsmd.getColumnName(i);
					String columnType = rsmd.getColumnClassName(i);

					if (columnType.equals("oracle.sql.BLOB")) {
						InputStream is = rs.getBinaryStream(columnName);
						// is.available()取的总是0 暂时用1024作为容器大小
						byte[] b = new byte[1024];
						byte[] buffer = null;
						if (is != null) {
							ByteArrayOutputStream baos = new ByteArrayOutputStream();
							int len = 0;
							while ((len = is.read(b)) != -1) {
								baos.write(b, 0, len);
							}
							buffer = baos.toByteArray();
						}
						valueTypeMap.put(buffer, columnType);
					} else if (columnType.equals("oracle.sql.CLOB")) {
						char[] clob = null;
						if (rs.getCharacterStream(columnName) != null) {
							BufferedReader breader = new BufferedReader(
									rs.getCharacterStream(columnName));
							String result = "";
							String temp = breader.readLine();
							while (temp != null) {
								result += temp + "\r\n";
								temp = breader.readLine();
							}
							clob = result.toCharArray();
						}
						valueTypeMap.put(clob, columnType);
					} else if (columnType.equals("java.sql.Timestamp")) {
						Date d = rs.getDate(columnName);
						valueTypeMap.put(d, columnType);
					} else {
						String s = rs.getString(columnName);
						valueTypeMap.put(s, columnType);
					}
					rows.put(columnName, valueTypeMap);
				}
				table.add(rows);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return table;
	}
}
